var ImageLoader = (function () {
	function ImageLoader() {
		this.states = {};
		this.images = {};
		this.handlers = {};
		this._finished = false;
	}

	ImageLoader.prototype = {
		setUseWowprogramming: function (flag) {
			this._use_wowprogramming = flag;
			for (var url in this.images) {
				var img = this.images[url];
				img.src = this._getUrl(url);
			}
		},
		_getUrl: function (url) {
			if (this._use_wowprogramming)
				return url.replace(/^Interface\//, "http://wowprogramming.com/BlizzArt/");
			else
				return url;
		},
		fetch: function (url, handler) {
			if (!this.images[url]) {
				this.states[url] = false;
				this.handlers[url] = [handler];
				var img = new Image();
				this.images[url] = img;
				img._IL = this;
				img._url = url;
				img.onload = function () {
					var il = img._IL;
					var url = img._url;
					il._onLoad(img, url);
				}
				img.src = this._getUrl(url);
			} else {
				if (!this.states[url]) {
					this.handlers[url].push(handler);
				} else {
					handler(img);
				}
			}
		},
		_onLoad: function (img, url) {
			var handlers = this.handlers[url];
			delete this.handlers[url];
			this.states[url] = true;
			if (handlers) {
				for (var i = 0; i < handlers.length; ++i) {
					handlers[i](img);
				}
			}
			this.finished();
		},
		setFinished: function () {
			this._finished = true;
			this.finished();
		},
		finished: function () {
			if (this._finished) {
				var found = false;
				for (var i in this.states) {
					if (!this.states[i]) {
						found = true;
						break;
					}
				}
				if (!found) redraw();
			}
		},
	}

	return new ImageLoader();
})();
